package net.bolue.sysmng.model;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.bolue.console.model.BusiBase;
import net.bolue.sysmng.db.DbOpUtil;
import net.bolue.sysmng.exception.BolueException;
import net.bolue.sysmng.tblbean.MvcAction;
import net.bolue.web.report.RepConstants;

/**
 * mvc资源业务
 * @author Administrator
 *
 */
public class MvcResModel extends BusiBase{
	
	public MvcResModel() {
		super();
	}

	public MvcResModel(HttpServletRequest request) {
		super(request);
	}

	/**
	 * 获得mvcaction
	 * @param action	格式：子系统.动作标识，如sysmng.insert
	 * @return
	 * @throws BolueException
	 */
	public MvcAction findMvcAction(String action) throws BolueException{
		if(action==null||"".equals(action)){
			return null;
		}
		if(action.indexOf(".")<0){
			return null;
		}
		String[] s = action.split("\\.");
		String subSys = s[0];
		String actId = s[1];
		MvcAction mvcAction = null;
		if(request==null){
			return mvcAction;
		}
		ServletContext application = request.getSession().getServletContext();
		Map<String,Map<String,MvcAction>> subMvcMap = (Map<String,Map<String,MvcAction>>)application.getAttribute("sysmngMvcActionRes");
		if(subMvcMap==null){
			subMvcMap = new HashMap<String,Map<String,MvcAction>>();
			application.setAttribute("sysmngMvcActionRes", subMvcMap);
		}
		Map<String,MvcAction> mvcActionMap = subMvcMap.get(subSys);
		if (mvcActionMap != null){
			mvcAction = mvcActionMap.get(actId);
		}else{
			mvcActionMap = new HashMap<String,MvcAction>();
			subMvcMap.put(subSys, mvcActionMap);
		}
		
		if(mvcAction==null){
			mvcAction = findMvcAction(subSys,actId);
			if(mvcAction!=null){
				mvcActionMap.put(actId, mvcAction);
			}
		}
		
		if(mvcAction==null){
			throw new BolueException(10, "没有找到SUBSYS=" + subSys + ",ACTID=" + actId + "的MVC资源。");
		}
		return mvcAction;
	}
	
	/**
	 * 获得mvcaction
	 * @param subSys	子系统
	 * @param actId		动作标识
	 * @return
	 * @throws BolueException
	 */
	public MvcAction findMvcAction(String subSys,String actId) throws BolueException{
		Map<String,Object> whereMap = new HashMap<String,Object>();
		whereMap.put("SUBSYS", subSys);
		whereMap.put("ACTID", actId);
		DbOpUtil dbOpUtil = new DbOpUtil(RepConstants.SYSMNG_SUBSYS_KEY);
		MvcAction mvcAction = dbOpUtil.getOne(MvcAction.class, "st_mvcaction", null, whereMap);
		return mvcAction;
	}
}
